import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import axios from "axios";
import '../public/base.css';

const BASE_URL = 'http://localhost:8080';
window.BASE_URL = BASE_URL;
const app = createApp(App)
app.config.globalProperties.BASE_URL = BASE_URL;
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.use(ElementPlus, {locale: zhCn}).use(store).use(router).mount('#app')

const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}

// 配置全局方法，获取当前登录人的数据
window.getUser = () => {
    return localStorage.user ? JSON.parse(localStorage.user) : null;
    // parse 将接收到的字符串转序列化
}
// 路由守卫

router.beforeEach((to, from, next) => {
    let user = localStorage.user;//从localStorage中获取用户数
    if (to.path !== '/login' && !user)//如果目标路径不是登录页且用户不存在
        // 就跳转到登录页，且弹出提示
        next({path: '/login'}, ElMessage({
                message: '请先登录',
                type: 'error',
                showClose: true,
                center: true,
            })
        )
    else
        next()//如果目标路径是登录页,或用户已登录,就直接放行,允许路由跳转
})

window.errorInfo = (info) => {
    ElMessage({
        message: info,
        type: 'error',
        showClose: true,
        center: true,
    })
}
window.OKInfo = (info) => {
    ElMessage({
        message: info,
        type: 'success',
        showClose: true,
        center: true,
    })
}
window.Info = (info) => {
    ElMessage({
        message: info,
        type: 'info',
        showClose: true,
        center: true,
    })
}

window.loadDictOptions = (object, dictCode) => {
    axios.get(BASE_URL+'/v1/dictOption/select/'+dictCode)
        .then((response) => {
            if (response.data.code === 2000) {
                object.value = response.data.data;
            } else {
                ElMessage({
                    message: response.data.message,
                    type: 'error',
                    showClose: true,
                    center: true,
                })
            }
        })
}